/**
 * 
 */
package com.p2p.base.service.impl;

import java.io.File;
import java.util.Map;

import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import com.p2p.base.model.MailTemplate;
import com.p2p.base.service.EmailService;
import com.p2p.base.util.mail.SendCloudMail;

import freemarker.template.Template;

/**
 * 
 * leiwen@yiqihao.com
 */
public class EmailServiceImpl implements EmailService {

	private static final String ENCODING = "utf-8";

	/*
	 * 发html格式邮件
	 */
	public void sendEmail(MailTemplate mailTemplate, String toEmail,
			Map<String, Object> model, Map<String, File> attachMap) {
		String encodeText = mailTemplate.getSubject();
		String mailText;
		try {
			mailText = getMailText(mailTemplate.getFtlTemplate(), model);
			SendCloudMail.send(toEmail, encodeText, mailText);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 通过模板构造邮件内容
	 */
	public String getMailText(Template template, Map<String, Object> model)
			throws Exception {
		// 通过指定模板名获取FreeMarker模板实例
		// Template template =
		// freeMarkerConfigurer.getConfiguration().getTemplate("registe.html");

		// 解析模板并替换动态数据，最终content将替换模板文件中的${content}标签。
		String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(
				template, model);
		System.out.println(htmlText);
		return htmlText;
	}
}
